package com.justrun.zjutsystem.zjutsystem.controller;


import com.justrun.annotations.ApiLog;
import com.justrun.response.ResultCodeEnum;
import com.justrun.response.ResultEntity;
import com.justrun.utils.EncryptUtil;
import com.justrun.zjutsystem.zjutsystem.authsecurity.ShiroUtils;
import com.justrun.zjutsystem.zjutsystem.dtos.UserDto;
import com.justrun.zjutsystem.zjutsystem.entity.SysUser;
import com.justrun.zjutsystem.zjutsystem.entity.SysUserRole;
import com.justrun.zjutsystem.zjutsystem.service.SysUserRoleService;
import com.justrun.zjutsystem.zjutsystem.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 学院信息表 前端控制器
 * </p>
 *
 * @author chandler
 * @since 2020-09-17
 */
@Slf4j
@Api("用户前端控制器")
@RestController
@RequestMapping("/zjutsystem/user")
@CrossOrigin
public class UserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @ApiOperation("添加用户")
    @PostMapping("/save")
    public ResultEntity addUser(@RequestBody UserDto userDto){
        if (userDto == null || userDto.getUserName() == null
             || userDto.getPasssword() == null){
            return ResultEntity.fail().code(ResultCodeEnum.REQUEST_PARAM_ERROR.getCode())
                    .message(ResultCodeEnum.REQUEST_PARAM_ERROR.getMesssage());
        }
        return sysUserService.addUser(userDto);
    }

    /**
     * 登录
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public ResultEntity login(@RequestBody  UserDto userDto){
        //进行身份验证
        try{
            //验证身份和登陆
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userDto.getUserName(), userDto.getPasssword());
            //进行登录操作
            subject.login(token);
        }catch (IncorrectCredentialsException e) {
            return ResultEntity.fail().code(ResultCodeEnum.ACCOUNT_OR_PASSWORD_ERROR.getCode())
                    .message(ResultCodeEnum.ACCOUNT_OR_PASSWORD_ERROR.getMesssage());
        } catch (LockedAccountException e) {
            return ResultEntity.fail().code(ResultCodeEnum.ACCOUNT_NOT_EXIST.getCode())
                    .message(ResultCodeEnum.ACCOUNT_NOT_EXIST.getMesssage());
        } catch (AuthenticationException e) {
            return ResultEntity.fail().code(ResultCodeEnum.ACCOUNT_NOT_EXIST.getCode())
                    .message(ResultCodeEnum.ACCOUNT_NOT_EXIST.getMesssage());
        } catch (Exception e) {
            return ResultEntity.fail().code(ResultCodeEnum.UNKOWN_ERROR.getCode())
                    .message(ResultCodeEnum.UNKOWN_ERROR.getMesssage());
        }
        //登录成功返回token
        return ResultEntity.ok().data(ShiroUtils.getSession().getId().toString());
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public ResultEntity logOut(){
        ShiroUtils.logout();
        return ResultEntity.ok();
    }
    /**
     * 未登录
     */
    @GetMapping("/unauth")
    public ResultEntity unauth(){
        return ResultEntity.fail().code(ResultCodeEnum.NO_LOGIN.getCode())
                .message(ResultCodeEnum.NO_LOGIN.getMesssage());
    }


    /**
     * 添加一个用户演示接口
     */
    @PostMapping("/addUser")
    @ApiLog(description = "添加用户")
    public ResultEntity testAddUser(@RequestBody UserDto userDto){
        // 设置基础参数
        SysUser sysUser = new SysUser();
        sysUser.setUsername(userDto.getUserName());
        sysUser.setState("NORMAL");
        // 账号前六位字符作为盐值
        String salt = userDto.getUserName().substring(0,6);
        sysUser.setSalt(salt);
        // 进行加密
        sysUser.setPassword(EncryptUtil.sha256Encrypt(userDto.getPasssword(), salt));
        // 保存用户
        boolean result1 = sysUserService.save(sysUser);
        // 保存角色
        SysUserRole sysUserRoleEntity = new SysUserRole();
        sysUserRoleEntity.setUserId(sysUser.getUserId()); // 保存用户完之后会把ID返回给用户实体
        sysUserRoleEntity.setRoleId(userDto.getRoleId());
        boolean result2 = sysUserRoleService.save(sysUserRoleEntity);
        // 返回结果
        if (result1 && result2){
            return ResultEntity.ok();
        }else {
            return ResultEntity.fail();
        }
    }
}
